import { useState, useRef, useEffect, useContext, RefObject } from 'react';
import { Button, Modal, Space, Form, Select, FormInstance, Input, message } from 'antd';
import { AgentSchema, PartySchema } from '@src/components/schema/caseSchema'
import Dictionary, { DictionaryItem } from '@js/dictionary';
import { CaseContext } from '@src/pages/admin/pages/caseDetail/context'
import { checkIdCard } from '@js/identityTest';
import AutoNameInput from '../autoNameInput'
import { addPartyRequest, updatePartyRequest } from './ajax'
import { awaitWrap, confirmAction } from '@src/assets/js/tool';

const { Item } = Form
const { Option } = Select
const { TextArea } = Input

const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 }
}


// 获取默认值
function getInitialValues (party: PartySchema | null, caseid: string, type: string, typeList: DictionaryItem[], companyLicenseTypes: DictionaryItem[]) {
  const subjectType = typeList[0] || {}
  const ctypes = (companyLicenseTypes || []).map(li => li.title)
  if (party) {
    return {
      ...party,
      caseid,
      action_subject: type
    }
  }
  return {
    caseid,
    type,
    name: undefined, // 全称姓名
    subject_type: subjectType.value, // 主体类型（企业、自然人、非法人组织）
    subject_type_tag: subjectType.title, // 主体详细类型（如：国企）
    license_type: ctypes[0] || '', // 证照类型
    license: undefined, // 证照号
    legal: undefined, // 法定代表人（自然人为空）
    address: undefined, // 详细住所
    area: '本地', // 区域信息（当事人所在地）
    mobile: undefined, // 手机号
    email: undefined, // 邮箱
    tel: undefined // 其他联系方式
  }
}

// 改变主体
function changeSubject (
  o: DictionaryItem,
  formRef: RefObject<FormInstance>,
  companyLicenseTypes: DictionaryItem[],
  licenseTypeList: DictionaryItem[],
  setModelType: (v: string) => void
) {
  const c = formRef.current
  if (!c) {
    return undefined
  }
  let licenseType = c.getFieldValue('license_type')
  if (['企业', '非企业组织'].indexOf(o.value) !== -1) {
    licenseType = companyLicenseTypes.indexOf(licenseType) === -1 ? companyLicenseTypes[0].title : licenseType
  } else {
    licenseType = licenseTypeList.indexOf(licenseType) === -1 ? licenseTypeList[0].title : licenseType
  }
  setModelType(o.value)
  c.setFieldsValue({
    subject_type: o.value,
    subject_type_tag: o.title,
    license_type: licenseType
  })
}

// 验证身份证
function validateLicense (formRef: RefObject<FormInstance>, value: string) {
  const type = formRef.current?.getFieldValue(['license_type'])
  if (type === '身份证' && value && value.length) {
    const e = checkIdCard.test(value)
    if (e) {
      return Promise.reject(new Error(e))
    }
  }
  return Promise.resolve()
}

// 根据主体类型渲染特定字段
function NameInputByType (
  formRef: RefObject<FormInstance>,
  type: string,
  companyLicenseTypes: DictionaryItem[],
  licenseTypeList: DictionaryItem[],
  typeList: DictionaryItem[]
) {
  let name = '公司名称'
  let legal = '法定代表人'
  let licenseTypes = companyLicenseTypes
  if (type === '自然人') {
    name = '姓名'
    licenseTypes = licenseTypeList
  } else if (type === '非企业组织') {
    name = '组织名称'
    legal = '负责人'
  }
  return (
    <>
      <Item label={name} name='name' rules={[{ required: true, message: `${name}不能为空` }]}>
        <AutoNameInput typeList={typeList} name={name} formRef={formRef} type={type} />
      </Item>
      <Item label='证件类型' name='license_type'>
        <Select
          placeholder='请选择证件类型' onChange={e => {
            formRef.current?.setFieldsValue({ license_type: e })
            formRef.current?.validateFields([['license']])
          }}
        >
          {licenseTypes.map((li, i) => (
            <Option value={li.title} key={i}>{li.title}</Option>
          ))}
        </Select>
      </Item>
      <Item label='证件号码' name='license' rules={[{ validator: (rule, value) => validateLicense(formRef, value) }, { required: true, message: '请输入证件号码' }]}>
        <Input placeholder='请输入证件号码' />
      </Item>
      {['企业', '非企业组织'].indexOf(type) !== -1 ? (
        <Item label={legal} name='legal'>
          <Input placeholder={`请输入${legal}`} />
        </Item>
      ) : null}
    </>
  )
}

async function submitHandle (data: {[k: string]: any}, caseid: string, type: string, refreshFn: () => void) {
  let fn: (v: any) => Promise<any> = addPartyRequest
  data.caseid = caseid
  data.action_subject = type
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  data.license = data.license || ''
  if (data.id) {
    fn = updatePartyRequest
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(fn(data))
  h()
  if (e === null) {
    refreshFn()
  }
}

function changeStatus (value: PartySchema, agentList: AgentSchema[], type: string, refreshFn: () => void) {
  if (value.status === 1) {
    const agents = getAgentName(value.id, agentList)
    if (agents.length) {
      Modal.warning({
        title: '提示',
        content: `${value.name} 已委托了代理人（${agents.join('、')}），请先解除代理关系后再删除${type} ${value.name}。`,
        okText: '确定'
      })
      return undefined
    }
    updateStatus(value, 0, refreshFn)
  } else {
    confirmAction(`您确定要将 ${value.name} 重新加入案件吗？`, () => {
      updateStatus(value, 1, refreshFn)
    })
  }
}

function getAgentName (id: string, agentList: AgentSchema[]) {
  const l: string[] = []
  agentList.forEach(a => {
    const ids = a.party.map(li => li.partyid)
    if (ids.includes(id)) {
      l.push(a.name)
    }
  })
  return l
}

async function updateStatus (data: PartySchema, status: number, refreshFn: () => void) {
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(updatePartyRequest({ ...data, status }))
  hide()
  if (e === null) {
    refreshFn()
  }
}

interface Props {
  value: PartySchema | null
  type: string
  visible: boolean
  editable: boolean
  hide: () => void
  agentList: AgentSchema[]
}

function Main ({ value, type, visible, agentList, editable, hide }: Props) {
  const c = useContext(CaseContext)
  const formRef = useRef<FormInstance>(null)
  const [typeList, setTypeList] = useState<DictionaryItem[]>([])
  const [companyLicenseTypes, setCompanyLicenseTypes] = useState<DictionaryItem[]>([])
  const [licenseTypeList, setLicenseTypeList] = useState<DictionaryItem[]>([])
  const [areaList, setAreaList] = useState<DictionaryItem[]>([])
  const [modelType, setModelType] = useState('')
  useEffect(() => {
    const d = new Dictionary()
    d.init('主体类型,所在地,自然人证件类型,企业证件类型')
      .then(() => {
        setTypeList(d.getList('主体类型'))
        setCompanyLicenseTypes(d.getList('企业证件类型'))
        setLicenseTypeList(d.getList('自然人证件类型'))
        setAreaList(d.getList('所在地'))
      }).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    if (visible) {
      const current = formRef.current
      const d = getInitialValues(value, c.caseid, type, typeList, companyLicenseTypes)
      if (current) {
        current.setFieldsValue(d)
      }
      setModelType(d.subject_type || '')
    } else {
      const current = formRef.current
      if (current) {
        current.resetFields()
      }
    }
  }, [value, visible, formRef])
  return (
    <div>
      <Modal
        title={value ? ( editable ? `修改${type}` : `${type}详情` ) : `添加${type}`}
        visible={visible}
        onCancel={() => hide()}
        maskClosable={false}
        width='700px'
        footer={(
          <Space>
            {value && editable && <Button danger onClick={() => { changeStatus(value, agentList, type, () => { c.initCaseDetail(); hide() }) }}>{value.status ? '撤销' : '恢复'}</Button>}
            <Button onClick={() => hide()}>取消</Button>
            {editable && <Button type='primary' onClick={() => formRef.current?.submit()}>确定</Button>}
          </Space>
        )}
      >
        <Form ref={formRef} {...layout} onFinish={(d) => submitHandle(d, c.caseid, type, () => { c.initCaseDetail(); hide() })}>
          <Item name='action_subject' noStyle><span /></Item>
          <Item name='id' noStyle><span /></Item>
          <Item name='subject_type' noStyle><span /></Item>
          <Item label='当事人主体' name='subject_type_tag' rules={[{ required: true }]}>
            <Select placeholder='请选择当事人主体' onChange={v => changeSubject(typeList[v], formRef, companyLicenseTypes, licenseTypeList, setModelType)}>
              {typeList.map((li, i) => (
                <Option value={i} key={li.title}>{li.title}</Option>
              ))}
            </Select>
          </Item>
          {NameInputByType(formRef, modelType, companyLicenseTypes, licenseTypeList, typeList)}
          <Item label='住所' name='address' rules={[{ required: false, message: '住所不能为空' }]}>
            <TextArea placeholder='请输入住所' style={{ resize: 'none' }} />
          </Item>
          <Item label='当事人所在地' name='area' rules={[{ required: true, message: '当事人所在地不能为空' }]}>
            <Select placeholder='请选择当事人所在地'>
              {areaList.map((li, i) => (
                <Option value={li.title} key={i}>{li.title}</Option>
              ))}
            </Select>
          </Item>
          <Item label='手机号码' name='mobile' rules={[{ pattern: /^1\d{10}$/, message: '手机号码格式不正确' }]}>
            <Input placeholder='请输入手机号码' maxLength={11} />
          </Item>
          <Item label='邮箱' name='email' rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
            <Input placeholder='请输入邮箱' />
          </Item>
          <Item label='其他联系方式' name='tel'>
            <Input placeholder='请输入其他联系方式' />
          </Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Main